import { http } from "@/utils/http";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useLocationParams } from "@/store/useLocationStore";
import { objToQueryString } from "@/utils/url";
import { domain } from "./useAuthStore";

export const useUserStore = defineStore("user", () => {
  const user = ref<UserInfo | null>(
    JSON.parse(localStorage.getItem("user") || "null")
  );
  const { getAllParams } = useLocationParams();

  const currentDealer = computed(() => {
    return user.value?.dealerList[0];
  });

  function setUser(data: UserInfo) {
    user.value = data;
    localStorage.setItem("user", JSON.stringify(data));
  }

  function clearUser() {
    localStorage.removeItem("user");
    user.value = null;
  }

  function isAuthenticated(): boolean {
    return user.value !== null;
  }

  async function auth(auth) {
    try {
      const data = await http.request<UserInfo>({
        url: "/auth/info",
        method: "GET",
        params: { auth },
        headers: {
          "No-Auth": true
        }
      });
      if (data) {
        setUser(data);
      }
    } catch (error) {
      console.error("Auth failed:", error);
    }
  }

  function wechatLogin(routePath = "") {
    const gzhId = import.meta.env.VITE_APP_ID; // 公众号appid
    const allParams = getAllParams();
    const query = objToQueryString(allParams);
    // let redirectUrl = `http://testmerchant.h5.pzmap.cn${import.meta.env.VITE_PUBLIC_PATH}`; // 授权回调链接
    // let redirectUrl = `${import.meta.env.VITE_REDIRECT_PATH}`;
    let redirectUrl = domain + "/userweb/login";

    const url = `${redirectUrl}${routePath}?${query}`; // 授权回调链接

    window.location.href =
      "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
      gzhId +
      "&redirect_uri=" +
      encodeURIComponent(url) +
      "&response_type=code&scope=snsapi_userinfo";
  }

  async function login(_data) {
    if (!_data.shopId) {
      _data.shopId = _data.spId;
    }
    try {
      const data = await http.request<UserInfo>({
        method: "POST",
        url: "/login/wxLogin",
        headers: {
          "No-Auth": true
        },
        data: _data
      });
      if (data) {
        setUser(data);
      }
      return data;
    } catch (error) {
      console.error("Login failed:", error);
    }
  }

  return {
    user,
    setUser,
    clearUser,
    isAuthenticated,
    wechatLogin,
    login,
    auth,
    currentDealer
  };
});
